package cn.iclass.modules.sys.oauth2;

import cn.iclass.modules.sys.entity.SysUserEntity;
import cn.iclass.modules.sys.service.ShiroService;
import cn.iclass.modules.sys.service.SysUserTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @Description: 认证
 * @Author: alan
 * @Date: 2019/6/10 5:59 PM
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {
	@Autowired
	private ShiroService shiroService;
	@Autowired
	private SysUserTokenService sysUserTokenService;

	@Override
	public boolean supports(AuthenticationToken token) {
		return token instanceof OAuth2Token;
	}

	/**
	 * 授权(验证权限时调用)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();
		Long userId = user.getUserId();

		//用户权限列表
		Set<String> permsSet = shiroService.getUserPermissions(userId);

		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(permsSet);
		return info;
	}

	/**
	 * 认证(登录时调用)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String accessToken = (String) token.getPrincipal();

		//根据accessToken，查询用户信息
		Long userId = sysUserTokenService.queryUserIdByToken(accessToken);
		//token失效
		if (userId == null) {
			throw new IncorrectCredentialsException("token失效，请重新登录");
		}

		//查询用户信息
		SysUserEntity user = shiroService.queryUser(userId);

		SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, accessToken, getName());
		return info;
	}
}
